package com.egdigital.allzic.ui.fragment;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserDepartment;
import com.egdigital.allzic.data.json.JsonParserStation;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Department;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.service.DownloadState;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterDepartment;
import com.egdigital.allzic.ui.adapter.AdapterListRadio;
import com.egdigital.allzic.utils.NetworkManager;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;

public class FragmentCategoryLocal extends BaseMainFragment implements OnItemClickListener, OnClickListener {

	private static final String		TAG					= FragmentCategoryLocal.class.getSimpleName();									// log
	private static final String		URL_BY_DEPARTMENT	= "http://www.allzicradio.com/json/get_radios_by_department/FR/%s/0/100000";
	private JsonParserDepartment	mJsonParser;
	private JsonParserStation		mJsonParserStation;
	private Department				mCurrentDepartment;
	private List<Station>			mListStation;
	//
	private ImageView				mImageArrowBack;
	private ListView				mListView;
	private TextView				mTitle;
	private RelativeLayout			mHeaderLayout;
	private AdapterDepartment		mAdapter;
	private AdapterListRadio		mAdapterRadio;
	private ImageButton				mCloseButton;
	// network ui
	protected ActivityMain			mParent;
	protected View					mView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_category_local, container, false);
		mLoadingView = (RelativeLayout) mView.findViewById(R.id.fragment_cat_local_loading);
		mReloadView = (LinearLayout) mView.findViewById(R.id.fragment_cat_local_reload);
		mNoResultView = (TextView) mView.findViewById(R.id.fragment_cat_local_noresult);
		//
		mListView = (ListView) mView.findViewById(R.id.fragment_cat_local_list);
		mTitle = (TextView) mView.findViewById(R.id.fragment_cat_local_title);
		mCloseButton = (ImageButton) mView.findViewById(R.id.fragment_cat_local_close);
		mHeaderLayout = (RelativeLayout) mView.findViewById(R.id.fragment_cat_local_title_layout);
		mImageArrowBack = (ImageView) mView.findViewById(R.id.fragment_cat_local_back);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mListView.setOnItemClickListener(this);
		mCloseButton.setOnClickListener(this);
		mHeaderLayout.setOnClickListener(this);
		mImageArrowBack.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		mImageArrowBack.setVisibility(View.GONE);
		mTitle.setText(getString(R.string.fragment_category_local));
	}

	@Override
	public void onResume() {
		super.onResume();
		analyticsSendEvent("Local");
		VolleyManager.init(mParent);
		if (mParent != null) {
			setDepartmentCallBack();
			setStationCallBack();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		if (mCurrentDepartment == null) {
			mCurrentDepartment = mParent.getmListDepartment().get(position);
			loadDataStation(mCurrentDepartment);
			setBackButton(true, mParent.getmListDepartment().get(position).getTitle());
		} else {
			if (mListStation != null && position < mListStation.size()) {
				Station station = mListStation.get(position);
				mParent.prepareToPlay(station);
				mParent.showPlayerBanner();
				mParent.updatePlayerBanner();
			}
		}
	}

	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.fragment_cat_local_reload:
				Log.w(TAG, "click test");
				loadData();
				break;
			case R.id.fragment_cat_local_close:
				mParent.removeFragment();
				break;
			case R.id.fragment_cat_local_title_layout:
				if (!mDownloadState.equals(DownloadState.LOADING) && mCurrentDepartment != null) {
					setBackButton(false, getString(R.string.fragment_category_local));
					mCurrentDepartment = null;
					if (mParent.getmListDepartment() != null && !mParent.getmListDepartment().isEmpty()) {
						updateAdapter(mParent.getmListDepartment());
						setmDownloadState(DownloadState.LOADED); // the dept listalready exist
						setLoaded(mListView);
					}
				}
				break;
		}
	}

	/**
	 * fragment life cycle
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mParent.mExplorerSelected = false;
		mParent = null;
		if (mJsonParser != null) {
			mJsonParser.stopRequestQueue();
		}
		if (mJsonParserStation != null) {
			mJsonParserStation.stopRequestQueue();
		}
	}

	/**
	 * methods
	 */
	private void loadData() {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			mJsonParser.extractJsonObjectData(getString(R.string.url_get_department));
		} else {
			setReload(mListView);
		}
	}

	private void loadDataStation(Department dept) {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			if (mJsonParserStation != null && dept.getId() != null) {
				mJsonParserStation.extractJsonObjectData(String.format(URL_BY_DEPARTMENT, dept.getId()));
			}
		} else {
			setReload(mListView);
		}
	}

	private void updateAdapter(List<Department> list) {
		if (list == null) {
			return;
		}
		mAdapter = null;
		mAdapter = new AdapterDepartment(mParent.getApplicationContext(), list);
		setLoading(mListView);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		setLoaded(mListView);
	}

	private void updateAdapterStation(List<Station> list) {
		if (list == null) {
			return;
		}
		mAdapterRadio = null;
		mAdapterRadio = new AdapterListRadio(mParent.getApplicationContext(), list, R.layout.cell_list_radio);
		setLoading(mListView);
		mListView.setAdapter(mAdapterRadio);
		mListView.setOnItemClickListener(this);
		setLoaded(mListView);
	}

	/**
	 * animation
	 */
	@SuppressLint("NewApi")
	@Override
	public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
		Animation animation = super.onCreateAnimation(transit, enter, nextAnim);
		if (animation == null && nextAnim != 0) {
			animation = AnimationUtils.loadAnimation(getActivity(), nextAnim);
		}
		if (animation != null) {
			animation.setAnimationListener(new AnimationListener() {

				public void onAnimationEnd(Animation animation) {
					getView().post(new Runnable() {

						@Override
						public void run() {
							try {
								if (mCurrentDepartment == null && mParent.getmListDepartment() != null && !mParent.getmListDepartment().isEmpty()) {
									updateAdapter(mParent.getmListDepartment());
								} else {
									loadData();
								}
							} catch (Exception e) {
							}
						}
					});
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animation;
	}

	/**
	 * callback
	 */
	private void setStationCallBack() {
		if (mJsonParserStation == null) {
			mJsonParserStation = new JsonParserStation();
			mJsonParserStation.initAndStartRequestQueue();
		}
		mJsonParserStation.setJsonCallBack(new JsonCallBack() {

			public void downloadStarted() {
				setLoading(mListView);
			}

			public void downloadPercent(int percent) {
				// do nothing
			}

			public <T> void downloadCompleted(List<T> list) {
				if (mParent == null || list == null) {
					return;
				}
				if (!list.isEmpty()) {
					setLoaded(mListView);
					// sort
					Collections.sort(list, new Comparator<Object>() {

						public int compare(Object o1, Object o2) {
							Station p1 = (Station) o1;
							Station p2 = (Station) o2;
							return p1.getmTitle().compareToIgnoreCase(p2.getmTitle());
						}
					});
					mListStation = (List<Station>) list;
					//
					updateAdapterStation((List<Station>) list);
				} else {
					setNoResult(mListView);
				}
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				setReload(mListView);
			}
		});
	}

	private void setDepartmentCallBack() {
		if (mJsonParser == null) {
			mJsonParser = JsonParserDepartment.getInstance();
			mJsonParser.initAndStartRequestQueue();
		}
		mJsonParser.setJsonCallBack(new JsonCallBack() {

			public void downloadStarted() {
				setLoading(mListView);
			}

			public void downloadPercent(int percent) {
				// do nothing
			}

			public <T> void downloadCompleted(List<T> list) {
				if (mParent == null || list == null) {
					return;
				}
				if (!list.isEmpty()) {
					setLoaded(mListView);
					// sort
					Collections.sort(list, new Comparator<Object>() {

						public int compare(Object o1, Object o2) {
							Department p1 = (Department) o1;
							Department p2 = (Department) o2;
							return p1.getTitle().compareToIgnoreCase(p2.getTitle());
						}
					});
					mParent.setmListDepartment((List<Department>) list);
					//
					updateAdapter((List<Department>) list);
				} else {
					setReload(mListView);
				}
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				setReload(mListView);
			}
		});
	}

	private void setBackButton(boolean visible, final String title) {
		if (visible) {
			YoYo.with(Techniques.FadeOut).duration(500).withListener(new AnimatorListener() {

				@Override
				public void onAnimationStart(Animator arg0) {
				}

				@Override
				public void onAnimationRepeat(Animator arg0) {
				}

				@Override
				public void onAnimationEnd(Animator arg0) {
					mImageArrowBack.setVisibility(View.VISIBLE);
					mTitle.setText(title);
					YoYo.with(Techniques.FadeIn).duration(500).playOn(mTitle);
				}

				@Override
				public void onAnimationCancel(Animator arg0) {
				}
			}).playOn(mTitle);
		} else {
			YoYo.with(Techniques.FadeOut).duration(500).withListener(new AnimatorListener() {

				@Override
				public void onAnimationStart(Animator arg0) {
				}

				@Override
				public void onAnimationRepeat(Animator arg0) {
				}

				@Override
				public void onAnimationEnd(Animator arg0) {
					mImageArrowBack.setVisibility(View.GONE);
					mTitle.setText(title);
					YoYo.with(Techniques.FadeIn).duration(500).playOn(mTitle);
				}

				@Override
				public void onAnimationCancel(Animator arg0) {
				}
			}).playOn(mTitle);
		}
	}
}
